package com.wtgroup.demo.foo;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class BessiesFunction {

    private static int n;
    private static List<List<Integer>> adjList;
    private static boolean[] visited;
    private static int[] lowLink;
    private static int[] ids;
    private static Stack<Integer> stack;
    private static int idCounter;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        int[] a = new int[n];
        int[] c = new int[n];

        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt() - 1; // Adjusting to 0-indexed array
        }

        for (int i = 0; i < n; i++) {
            c[i] = scanner.nextInt();
        }

        adjList = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adjList.add(new ArrayList<>());
        }
        for (int i = 0; i < n; i++) {
            if (a[i] != i) { // Only add edge if it doesn't point to itself.
                adjList.get(i).add(a[i]);
            }
        }

        visited = new boolean[n];
        lowLink = new int[n];
        ids = new int[n];
        stack = new Stack<>();
        idCounter = 0;

        int result = 0;
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                dfs(i, c, result);
            }
        }

        System.out.println(result);
    }

    private static int dfs(int at, int[] costs, int result) {
        stack.push(at);
        visited[at] = true;
        lowLink[at] = ids[at] = idCounter++;

        for (int to : adjList.get(at)) {
            if (!visited[to]) {
                result = dfs(to, costs, result);
                lowLink[at] = Math.min(lowLink[at], lowLink[to]);
            } else if (stack.contains(to)) {
                lowLink[at] = Math.min(lowLink[at], ids[to]);
            }
        }

        if (ids[at] == lowLink[at]) {
            int node;
            int minCost = Integer.MAX_VALUE;
            do {
                node = stack.pop();
                minCost = Math.min(minCost, costs[node]);
            } while (node != at);

            result += minCost;
        }

        return result;
    }
}
